package com.rc.evcharger.controller;

import com.github.pagehelper.util.StringUtil;
import com.google.gson.Gson;
import com.rc.evcharger.biz.utils.PubFetchTool;
import com.rc.evcharger.common.base.TResponse;
import com.rc.evcharger.common.constant.HttpConstant;
import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.common.enums.CommanderEnum;
import com.rc.evcharger.model.elec.ElecGun;
import com.rc.evcharger.model.elec.ElecPile;
import com.rc.evcharger.model.hlhtsk.HlhtskTenant;
import com.rc.evcharger.model.order.OrderInfo;
import com.rc.evcharger.protocol.ylevcharger.service.YlCommandService;
import com.rc.evcharger.service.elec.ElecGunService;
import com.rc.evcharger.service.elec.ElecPileService;
import com.rc.evcharger.service.hlhtsk.HlhtskTenantService;
import com.rc.evcharger.service.order.OrderInfoService;
import com.rc.evcharger.vo.cec.StdRequest;
import com.rc.evcharger.vo.charge.CommandStartReq;
import com.rc.evcharger.vo.charge.CommandStopReq;
import com.rc.evcharger.vo.charge.StartChargeReq;
import com.rc.evcharger.vo.charge.StopChargeReq;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 非标准协议
 * 自充和内联充电，微信充电接口，需解密
 */
@RestController
@RequestMapping(value = {"/app", "/mini"})
public class ChargeController {
    private static Logger logger = LogManager.getLogger(ChargeController.class);

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private HlhtskTenantService hlhtskTenantService;

    @Autowired
    private YlCommandService ylCommandService;

    /**
     * 开始充电，微信启动充电没有外部订单号
     */
    @RequestMapping(value = "/query_start_charge", method = RequestMethod.POST)
    public TResponse query_start_charge(@RequestBody StdRequest tRequest) {
        try {
            String tenantCode = tRequest.getSeq();  //Seq存储tenantCode
            String hlhtTenantCode = tRequest.getOperatorID(); //OperatorID存储hlhtTenantCode;

            HlhtskTenant hlhtskTenant = null;
            if (hlhtTenantCode == null) {//自充
                hlhtskTenant = hlhtskTenantService.selectHlhtTenantByTenantCode(tenantCode);
            } else {//内联充电
                hlhtskTenant = hlhtskTenantService.selectBetweenTenantCode(tenantCode, hlhtTenantCode);
            }

            //解密
            String data = PubFetchTool.genDDDecodeData(hlhtskTenant, tRequest.getData());
            logger.info("ChatChargeController.query_start_charge:data:{}", data);
            CommandStartReq commandStartReq = new Gson().fromJson(data, CommandStartReq.class);

            //封装至充电入参中
            StartChargeReq startChargeReq = new StartChargeReq();
            startChargeReq.setMemberId(commandStartReq.getMemberId());
//            startChargeReq.setCmdCode(SocketConstant.POWER_START);
            startChargeReq.setElecPileId(commandStartReq.getElecPileId());
            startChargeReq.setGunNum(commandStartReq.getGunNum());
            startChargeReq.setTicketUsingType(commandStartReq.getTicketUsingType());
            //外部订单号
            startChargeReq.setOutOrderNum(commandStartReq.getOutOrderNum());
            startChargeReq.setTenantCode(commandStartReq.getTenantCode());  //运营商
            startChargeReq.setTenantOperatorCode(commandStartReq.getTenantOperatorCode());//分销商
            startChargeReq.setHlhtTenantCode(commandStartReq.getHlhtTenantCode());//SAAS互联互通运营商
            startChargeReq.setHlhtOperatorId(commandStartReq.getHlhtOperatorId());//第三方运营商
            startChargeReq.setCarNum(commandStartReq.getCarNum());  //车牌号
            startChargeReq.setStartType(commandStartReq.getStartType());
            startChargeReq.setStartValue(commandStartReq.getStartValue()); //充电策略单位
            startChargeReq.setMemberTicketIds(commandStartReq.getMemberTicketIds());
            startChargeReq.setIsUseGiveAmount(commandStartReq.getIsUseGiveAmount());

            //防止为空的情况
            if (startChargeReq.getTicketUsingType() == null || "".equals(startChargeReq.getTicketUsingType())) {
                startChargeReq.setTicketUsingType(SocketConstant.CON0 + "");
            }

            if (commandStartReq.getStartValue() == null) {
                startChargeReq.setStartValue("0");
            }

            //支付的账户类型 0个人钱包 1企业钱包 默认0
            startChargeReq.setAccountType(commandStartReq.getAccountType());

            //发送通讯指令(订单来源(订单来源(0 公众号 1 APP 2小程序 3.刷卡 4.第三方API 默认0))

            if (startChargeReq.getOrderSource() == null) {
                startChargeReq.setOrderSource(CommanderEnum.MINI_PROGRAM.getCode());
            }
            logger.info("query_start_charge 入参:{}", startChargeReq.toString());

            if (startChargeReq.getElecPileId() == null) {
                return TResponse.FAIL("找不到电桩");
            }

            //支付的账户类型 0个人钱包 1企业钱包 默认0
            if (StringUtils.isBlank(startChargeReq.getAccountType())) {
                startChargeReq.setAccountType("0");
            }

            ElecPile elecPile = elecPileService.selectByPrimaryKey(startChargeReq.getElecPileId());
            if (elecPile.getStatus().equals(SocketConstant.OFF_LINE)) {
                return TResponse.FAIL("电桩已离线");
            }

            ElecGun gun;
            if (StringUtils.isNotBlank(commandStartReq.getGunNo())) {
                gun = elecGunService.selectGunByGunNo(commandStartReq.getGunNo());
                if (gun == null) {
                    return TResponse.FAIL("找不对应的枪");
                }
            } else {
                gun = elecGunService.validGun(elecPile, commandStartReq.getGunNum());
            }

            //使用状态 0 空闲 1使用中  2 插枪中 默认0
            if ("1".equals(gun.getStatus())) {
                return TResponse.FAIL("电枪已被使用");
            }

//            startChargeReq.setStartType("0");//启动方式 0 一般 1 刷卡 2 VIN码启动 默认0
            //判断启动方式
            if (StringUtil.isEmpty(startChargeReq.getStartType())) {
                startChargeReq.setStartType("0"); //默认0
            } else {
                startChargeReq.setStartType(commandStartReq.getStartType());//启动方式 0 一般 1 刷卡 2 VIN码启动 3.先付后退 默认0
            }

            Integer result = ylCommandService.query_start_charge(startChargeReq);
            if (result == null) {
                logger.error("找不到对应的厂家domian，无法发送指令,对应的domian:{}", elecPile.getElecServerDomain());
                return TResponse.FAIL("找不到对应的domain:" + elecPile.getElecServerDomain());
            }

            //如果不成功,返回各种错误码
            if (SocketConstant.SUCCESS == (result)) {
                return TResponse.SUCCESS();
            } else {
                switch (result) {
                    case SocketConstant.FAIL:
                        return TResponse.FAIL(SocketConstant.FAIL_SEND_CODE);
                    case SocketConstant.UNIQUE:
                        return TResponse.FAIL("发送指令重复");
                    case SocketConstant.EXCEPTION:
                        return TResponse.FAIL(HttpConstant.FAIL_CODE_501, "余额不足");
                    case SocketConstant.USING:
                        return TResponse.FAIL(HttpConstant.FAIL_CODE_502, "上次订单还没结算完，请稍等");
                    default:
                        return TResponse.FAIL("状态未知:" + result);
                }
            }
        } catch (Exception e) {
            logger.error("WeChatCmdController.query_start_charge", e);
            return TResponse.FAIL(SocketConstant.FAIL_SEND_CODE);
        }
    }

    /**
     * 停止充电
     */
    @RequestMapping(value = "/query_stop_charge", method = RequestMethod.POST)
    public TResponse query_stop_charge(@RequestBody StdRequest tRequest) {
        try {
            String tenantCode = tRequest.getSeq();  //Seq存储tenantCode
            String hlhtTenantCode = tRequest.getOperatorID(); //OperatorID存储hlhtTenantCode;

            HlhtskTenant hlhtskTenant = null;
            if (hlhtTenantCode == null) {//自充
                hlhtskTenant = hlhtskTenantService.selectHlhtTenantByTenantCode(tenantCode);
            } else {//内联充电
                hlhtskTenant = hlhtskTenantService.selectBetweenTenantCode(tenantCode, hlhtTenantCode);
            }

            //解密
            String data = PubFetchTool.genDDDecodeData(hlhtskTenant, tRequest.getData());
            CommandStopReq stopRequest = new Gson().fromJson(data, CommandStopReq.class);

            //封装至停止入参中
            StopChargeReq stopChargeReq = new StopChargeReq();
            stopChargeReq.setMemberId(stopRequest.getMemberId());
//            stopChargeRequest.setCmdCode(SocketConstant.POWER_STOP);
            stopChargeReq.setElecPileId(stopRequest.getElecPileId());
            stopChargeReq.setGunNum(stopRequest.getGunNum());
            stopChargeReq.setOrderId(stopRequest.getOrderId());

            logger.info("微信.query_stop_charge入参:{}", stopChargeReq.toString());

            if (stopChargeReq.getElecPileId() == null || stopChargeReq.getOrderId() == null) {
                return TResponse.FAIL("订单ID或电桩ID为空");
            }

            ElecPile elecPile = elecPileService.selectByPrimaryKey(stopChargeReq.getElecPileId());
            if (elecPile.getStatus().equals(SocketConstant.OFF_LINE)) {
                return TResponse.FAIL("电桩已离线");
            }

            ElecGun gun = elecGunService.validGun(elecPile, stopChargeReq.getGunNum());
            if (gun == null) {
                return TResponse.FAIL("找不对应的枪");
            }

            //验证订单
            OrderInfo order = orderInfoService.selectByPrimaryKey(stopChargeReq.getOrderId());
            if (order == null) {
                return TResponse.FAIL("订单ID不存在:{}");
            }
            stopChargeReq.setOrderNum(order.getOrderNum());
            stopChargeReq.setStopType(SocketConstant.STOP_NORMAL_0X0);


            Integer result = ylCommandService.query_stop_charge(stopChargeReq);
            if (result == null) {
                logger.error("找不到对应的厂家domian，无法发送指令,对应的domian:{}", elecPile.getElecServerDomain());
                return TResponse.FAIL("找不到对应的domain:" + elecPile.getElecServerDomain());
                //向智充桩发送充电指令(communic-->mq-->evcharger)
                //result = commandService.query_stop_charge(stopChargeRequest);
            }

            if (1 == result) {
                return TResponse.SUCCESS();
            } else {
                switch (result) {
                    case SocketConstant.FAIL:
                        return TResponse.FAIL(SocketConstant.FAIL_SEND_CODE);
                    case SocketConstant.UNIQUE:
                        return TResponse.FAIL("发送指令重复");
                    case SocketConstant.EXCEPTION:
                        return TResponse.FAIL(HttpConstant.FAIL_CODE_501, "余额不足");
                    case SocketConstant.USING:
                        return TResponse.FAIL(HttpConstant.FAIL_CODE_502, "上次订单还没结算完，请稍等");
                    default:
                        return TResponse.FAIL("状态未知:" + result);
                }
            }
        } catch (Exception e) {
            logger.error("MutiWeChatChargeController.query_stop_charge", e);
            return TResponse.FAIL(SocketConstant.FAIL_SEND_CODE);
        }
    }

}
